package com.hsy.swu.home.exam

import android.content.res.ColorStateList
import android.os.Bundle
import android.view.View
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.room.Room
import com.hsy.swu.R
import com.hsy.swu.databinding.FragmentExamBinding
import com.hsy.swu.databinding.ItemExamBinding
import com.hsy.swu.home.HomeFragmentViewModel
import com.hsy.swu.hsyutils.HsyFragment
import com.hsy.swu.hsyutils.MActivityUtil
import com.hsy.swu.hsyutils.MLog
import com.hsy.swu.hsyutils.addItem
import com.hsy.swu.roomdb.AppDatabase
import com.hsy.swu.roomdb.ExamDao
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class ExamFragment : HsyFragment<FragmentExamBinding, HomeFragmentViewModel>() {
    private lateinit var examDao: ExamDao

    override fun createViewModel(): HomeFragmentViewModel {
        return ViewModelProvider(requireActivity())[HomeFragmentViewModel::class.java]
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        examDao = Room.databaseBuilder(
            requireContext(),
            AppDatabase::class.java,
            "swu"
        ).build().examDao()
    }

    override fun onResume() {
        super.onResume()
        lifecycleScope.launch {
            showAllExam(mBinding.linearLayoutCompat)
        }
        mViewModel.mBinder?.getService()?.setGetExamListener { examList ->
            MLog.attention("get exam -> ${examList.size}")
            lifecycleScope.launch {
                if (isResumed) {
                    showAllExam(mBinding.linearLayoutCompat)
                }
            }
        }
    }

    // onPause清空内容，使得下次跳转到当前 fragment的显示效果更加丝滑
    override fun onPause() {
        super.onPause()
        mBinding.linearLayoutCompat.removeAllViews()
    }

    private suspend fun showAllExam(examLinearLayout: LinearLayoutCompat) {
        val examDBList: List<ExamModel>
        withContext(Dispatchers.IO) {
            examDBList = examDao.getAll()
        }
        examLinearLayout.removeAllViews()
        ExamModel.sortByGapDay(examDBList).forEach { examModel ->
            examLinearLayout.addExamItem(examModel)
        }

        if (examDBList.isNotEmpty()) {
            MActivityUtil.alphaAnimGoneLottieEmpty(mBinding.lottieEmpty)
        } else {
            MActivityUtil.alphaAnimVisibleLottieEmpty(mBinding.lottieEmpty)
        }
    }

    private suspend fun LinearLayoutCompat.addExamItem(examModel: ExamModel) {
        val itemBinding = ItemExamBinding.inflate(layoutInflater, this, false)
        itemBinding.apply {
            val examRemainingDay = examModel.getExamRemainingDay()
            tvStart.backgroundTintList = ColorStateList.valueOf(
                when {
                    examRemainingDay > 3 -> resources.getColor(R.color.blue)
                    examRemainingDay in 0..3 -> resources.getColor(R.color.red)
                    else -> resources.getColor(R.color.lightGray)
                }
            )
            tvStart.text = when {
                examRemainingDay == 0 -> "今日"
                examRemainingDay < 0 -> "必过"
                else -> "$examRemainingDay"
            }
            tvEventName.text = examModel.courseName
            tvEventInfo.text = "${examModel.time} | ${examModel.examRoom}"
            tvDate.text = examModel.date
        }
        addItem(itemBinding)
        itemBinding.root.animate().scaleX(0f).scaleY(0f).setDuration(0L).start()
        delay(10)
        MActivityUtil.scaleAnimOnShow(itemBinding.root)
    }
}